using System;
using System.Web.UI;
using xtra.domain.Subsonic3;
using sb.core.Framework;
using System.Collections.Generic;
using System.IO;
namespace sb.core {
    public partial class BaseUserControl : UserControl {
        public Plugins_In_Page CurrentNode { get; set; }
        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);
            RegisterLocalAssets();
        }
        private void RegisterLocalAssets() {
            if (this.Visible) {
                var path = TemplateControl.AppRelativeVirtualPath.Substring(0, TemplateControl.AppRelativeVirtualPath.LastIndexOf("/"));
                DirectoryInfo di = new DirectoryInfo(Server.MapPath(path));

                foreach (FileInfo item in di.GetFiles("*.css")) {
                    var url = path.Replace("~/", "").ToLower() + "/" + item;
                    SiteContext.Current.BaseMaster.HeaderHolderMiddle.Controls.Add(new LiteralControl(string.Format(@"<link rel=""stylesheet"" type=""text/css"" href=""{0}"" />{1}", url, Environment.NewLine)));
                }
                foreach (FileInfo item in di.GetFiles("*.js")) {
                    if (item.Length > 3) {
                        var url = path.Replace("~/", "").ToLower() + "/" + item;
                        SiteContext.Current.BaseMaster.HeaderHolderMiddle.Controls.Add(new LiteralControl(string.Format(@"<script type=""text/javascript"" src=""{0}"" ></script>{1}", url, Environment.NewLine)));
                    }
                }
            }
        }

        public string UIText(string codeName) {
            var ret = "UI Recource not found";

            var ui = SiteContext.Current.Repo.Single<UIResource>(a => a.ModuleId == CurrentNode.Id && a.CodeName == codeName);

            if (ui != null) {
                ret = ui.Value;
            } else {
                try {
                    ui = new UIResource();
                    ui.CodeName = codeName;
                    ui.Value = codeName; //TODO: make more friendly string
                    ui.ModuleId = CurrentNode.Id;
                    SiteContext.Current.Repo.Add(ui);
                    ret = ui.Value;
                } catch (Exception ex) {
                    throw ex;
                }
            }
            return ret;
        }
    }
}
